//
//  Formatter.swift
//  Yip
//
//  Created by bo wang on 2022/6/1.
//  Copyright © 2022 yip.com. All rights reserved.
//

import Foundation

extension Locale {
    /// 从货币单位缩写找到对应的Locale
    /// - Parameter code: 货币单位，符合ISO4217标准，比如 EUR
    /// - Returns: Locale
    static func localeWithCurrencyCode(_ code: String) -> Locale? {
        return Locale.availableIdentifiers
            .lazy
            .map({ Locale(identifier: $0) })
            .first { $0.currencyCode == code }
    }
    
    /// 从语言码找到对应的Locale
    /// - Parameter code: 语言
    /// - Returns: Locale
    static func localeWithLanguageCode(_ code: String) -> Locale? {
        return Locale.availableIdentifiers
            .lazy
            .map({ Locale(identifier: $0) })
            .first { $0.languageCode == code }
    }
}

extension Formatter {
    /// 从货币单位缩写找到对应的货币符号
    /// - Parameter currencyCode: 货币单位，符合ISO4217标准，比如 EUR
    /// - Returns: 货币符号，比如 €
    static func getCurrencySymbol(from currencyCode: String) -> String? {
        return Locale.localeWithCurrencyCode(currencyCode)?.currencySymbol
    }
}

/// 用于解析标准的ISO8601时间字符串。
/// 支持 2021-11-12T11:00:38.241Z   和 2021-11-12T11:00:38.241+00:00 格式
let serverDateFormatter: ISO8601DateFormatter = {
    let formatter = ISO8601DateFormatter()
    formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    return formatter
}()

func dateFromServerDateStr(_ dateStr: String) -> Date? {
    return serverDateFormatter.date(from: dateStr)
}

func serverDateStrFromDate(_ date: Date = Date()) -> String {
    return serverDateFormatter.string(from: date)
}
